import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
import seaborn as sns
import warnings
from config import config


# warnings.filterwarnings(action='once')
#
# params = config.PARAMS
# plt.rcParams.update(params)
# plt.style.use('seaborn-whitegrid')
# sns.set_style('white')


def plot(title=None):
    """
    画图
    :param title:
    :return:
    """
    # matplotlib中文显示方块
    mpl.rcParams['font.sans-serif'] = ['SimHei']  # 指定默认字体
    mpl.rcParams['axes.unicode_minus'] = False  # 解决保存图像是负号'-'显示为方块的问题

    if title:
        plt.title(title, fontsize=20)
    plt.show()


def scatter_lr_plot():
    """
    散点+线性回归线
    :return:
    """
    df = pd.read_csv('./data/mpg_ggplot2.csv')
    df_select = df.loc[df['cyl'].isin([4, 8]), :]

    print(df_select[['displ', 'hwy', 'cyl']].head())
    sns.set_style('white')

    # 将两类合并在一张图
    # hue是分类
    # aspect > 1 为拉长图片
    # gridobj = sns.lmplot(x='displ', y='hwy', hue='cyl', data=df_select, height=7, aspect=1.5,
    #                      palette='tab10', scatter_kws=dict(s=60, linewidths=0.7, edgecolor='black'))
    # 画图
    # plot(title='散点+线性回归线')

    # 将两类split成两个子图
    # palette参数
    gridobj = sns.lmplot(x='displ', y='hwy', data=df_select, height=7, palette='tab10', col='cyl',
                         scatter_kws=dict(s=60, linewidths=0.7, edgecolor='black'))
    # 画图
    plot()


def scatter_bubble_plot():
    """
    散点+泡图（数值大小）
    :return:
    """
    df = pd.read_csv('./data/mpg_ggplot2.csv')
    df_counts = df.groupby(['hwy', 'cty']).size().reset_index(name='counts')
    # print(df_counts)

    # stripplot：数据抖动，避免同一点的多个数据无法呈现
    sns.stripplot(x=df_counts['cty'], y=df_counts['hwy'], size=df_counts['counts'] * 2)

    plot(title='散点+泡图（数值大小）')


def corr_mtcats():
    """
    相关系数
    :return:
    """
    df = pd.read_csv('./data/mtcars.csv')
    # 整个dataframe的相关系数
    df_corr = df.corr()

    # annot=True：显示相关系数值
    # cmap：配色体系
    sns.heatmap(data=df_corr, xticklabels=df_corr.columns, yticklabels=df_corr.columns,
                cmap='RdYlGn', center=0, annot=True)

    plot(title='相关系数图')


def paiwise_plot():
    """
    矩阵图
    :return:
    """
    df = sns.load_dataset('iris')

    # kind为基本类型（散点图，折线图等）
    sns.pairplot(data=df, kind='scatter', hue='species')
    plot(title='矩阵图')


def diverg_bar():
    """
    发散型条形图
    :return:
    """
    # matplotlib中文显示方块
    mpl.rcParams['font.sans-serif'] = ['SimHei']  # 指定默认字体
    mpl.rcParams['axes.unicode_minus'] = False  # 解决保存图像是负号'-'显示为方块的问题

    df = pd.read_csv('./data/mtcars.csv')

    x = df[['mpg']]
    df['mpg_z'] = (x - x.mean()) / x.std()
    df['colors'] = ['red' if x < 0 else 'green' for x in df['mpg_z']]
    df.sort_values('mpg_z', inplace=True)
    df.reset_index(inplace=True)

    # 画图
    # plt.figure(figsize=(14, 10), dpi=80)
    plt.hlines(y=df.index, xmin=0, xmax=df['mpg_z'], colors=df['colors'],
               alpha=0.4, linewidth=5)
    # 增加数值
    for x, y, tex in zip(df['mpg_z'], df.index, df['mpg_z']):
        t = plt.text(x, y, round(tex, 2), horizontalalignment='right' if x < 0 else 'left',
                     verticalalignment='center',
                     fontdict={'color': 'red' if x < 0 else 'green', 'size': 7}
                     )

    # 设置
    plt.gca().set(ylabel='$Model$', xlabel='$Mileage$')
    # 重置y轴
    plt.yticks(df.index, df['cars'], fontsize=8)
    plt.title('发散型条形图', fontsize=20)
    # 设置网格线及粗细度
    plt.grid(linestyle='--', alpha=0.5)
    plt.show()


diverg_bar()
